package com.nand.module.function.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.Callback;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.base.utils.ObjectUtils;
import com.nand.library.base.utils.SpUtils;
import com.nand.library.zxing.activity.CaptureActivity;
import com.nand.library.zxing.activity.CodeUtils;
import com.nand.module.function.R;
import com.nand.module.function.bean.IdBean;
import com.nand.module.function.bean.IqbMateBean;
import com.nand.module.function.bean.MmhitchListBean;
import com.nand.module.function.bean.UnitBean;
import com.nand.module.function.constant.URL;
import com.nand.module.function.utils.LogUtils;
import com.nand.module.function.utils.ToolUtils;
import com.nand.module.function.view.AutoAdjustSizeEditText;
import com.nand.module.function.view.CommonPopupWindow;
import com.nand.module.function.view.AutofitTextView;
import com.nand.module.function.view.WheelView;


import java.util.ArrayList;
import java.util.List;

/**
 * created by 86185
 * on 2019/12/31
 */
public class IqcRegisterActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_CODE = 1001;
    private AutoAdjustSizeEditText mEtNumber;
    private String oid;
    private String supplierOid;
    private String supplierCode;
    private AutofitTextView mTvWlpcm;
    private TextView mTvWlbm;
    private TextView mTvWlmc;
    private TextView mTvGys;
    private TextView mTvWllb;
    private TextView mTvIqcmj, mTvKf, mTvTzbb, mTvWlrq, mTvBc, mTvDw;
    private CommonPopupWindow window, window2;
    private WheelView mWheelKf, mWheelDw;
    private EditText mEtSl, mEtPsl;
    private String number;
    private String substring;
    private int iqcNCheck;
    private String partID;
    private int userId;
    private TextView mTvLjcsd;
    private TextView mTvYxjD;
    private TextView mTvYxjZ;
    private TextView mTvYxjG;
    private TextView mTvBzWz;
    private TextView mTvBzBwz;
    private TextView mTvJybgWz;
    private TextView mTvJybgBwz;

    @Override
    protected int initLayout() {
        return R.layout.activity_iqc_register;
    }

    @Override
    protected void initView() {
        mActionBar().setCenterText("IQC来料登记");
        userId = SpUtils.readInt(this, "userId", 0);
        mEtNumber = findViewById(R.id.et_equipment_number);
        mTvWlpcm = findViewById(R.id.tv_wlpcm);
        mTvWlbm = findViewById(R.id.tv_wlbm);
        mTvWlmc = findViewById(R.id.tv_wlmc);
        mTvLjcsd = findViewById(R.id.tv_ljcsd);
        mTvGys = findViewById(R.id.tv_gys);
        mEtSl = findViewById(R.id.et_sl);
        mEtPsl = findViewById(R.id.et_psl);
        mTvWllb = findViewById(R.id.tv_wllb);
        mTvIqcmj = findViewById(R.id.tv_iqcmj);

        findViewById(R.id.ll_kf).setOnClickListener(this);
        findViewById(R.id.ll_dw).setOnClickListener(this);
        mTvKf = findViewById(R.id.tv_kf);
        mTvTzbb = findViewById(R.id.tv_tzbb);
        mTvWlrq = findViewById(R.id.tv_wlrq);
        mTvBc = findViewById(R.id.tv_bc);
        mTvDw = findViewById(R.id.tv_dw);
        mTvYxjD = findViewById(R.id.tv_yxj_d);
        mTvYxjZ = findViewById(R.id.tv_yxj_z);
        mTvYxjG = findViewById(R.id.tv_yxj_g);
        mTvBzWz = findViewById(R.id.tv_bz_wz);
        mTvBzBwz = findViewById(R.id.tv_bz_bwz);
        mTvJybgWz = findViewById(R.id.tv_jybg_wz);
        mTvJybgBwz = findViewById(R.id.tv_jybg_bwz);

        mTvYxjD.setOnClickListener(this);
        mTvYxjZ.setOnClickListener(this);
        mTvYxjG.setOnClickListener(this);
        mTvBzWz.setOnClickListener(this);
        mTvBzBwz.setOnClickListener(this);
        mTvJybgWz.setOnClickListener(this);
        mTvJybgBwz.setOnClickListener(this);
        mEtNumber.setText("1-000000031011100016-B2-10001-20200320-A-00001");
    }

    @Override
    protected boolean isActionBar() {
        return true;
    }

    @Override
    protected void initData() {
        OptionsPicker();
        OkGoUtils.getInstance().post(this, URL.STIRE_HOUSE_LIST, null, 1, false, mCallback);
        OkGoUtils.getInstance().post(this, URL.UNIT, null, 2, false, mCallback);
    }

    ArrayList<String> mKfList = new ArrayList<>();
    ArrayList<IdBean> mKfRawList = new ArrayList<>();
    ArrayList<String> mDwList = new ArrayList<>();
    ArrayList<IdBean> mDwRawList = new ArrayList<>();
    /**
     * 请求返回的处理
     */


    private MyCallback mCallback = new MyCallback() {
        @Override
        public void onSuccess(ResponseBean response, int id) {
            if (response.getCode() == 200) {
                String data = response.getDataInfo().toString();
                LogUtils.e("ac=============" + data);
                switch (id) {
                    case 1: //库房
                        LogUtils.e("data=========" + data);
                        MmhitchListBean listBeans = JSON.parseObject(data, MmhitchListBean.class);
                        List<MmhitchListBean.DataListBean> dataList = listBeans.getDataList();
                        for (int i = 0; i < dataList.size(); i++) {
                            IdBean idBean = new IdBean();
                            idBean.setId(dataList.get(i).getOid());
                            idBean.setType(dataList.get(i).getStoreName());
                            mKfList.add(dataList.get(i).getStoreName());
                            mKfRawList.add(idBean);
                        }
                        break;
                    case 2: //单位
                        List<UnitBean> unitBeans = JSON.parseArray(data, UnitBean.class);

                        for (int i = 0; i < unitBeans.size(); i++) {
                            IdBean idBean = new IdBean();
                            idBean.setId(unitBeans.get(i).getOid());
                            idBean.setType(unitBeans.get(i).getUnitname());
                            mDwList.add(unitBeans.get(i).getUnitname());
                            mDwRawList.add(idBean);
                        }
                        break;
                    case 3:

                        break;
                }

            } else {
                showToast(response.getMsg());
            }


        }

        @Override
        public void onError(Throwable e, int id) {
        }
    };

    private int yxjID = 0;
    private String yxjString = "低";
    private int bzID = 1;
    private int jybgID = 1;
    private int kfID = 10001;
    private int dwID = 10001;

    private OptionsPickerView kfPicker, dwPicker;

    private void OptionsPicker() {
        kfPicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                mTvKf.setText(mKfList.get(options1));
                kfID = mKfRawList.get(options1).getId();
            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(14)//确定和取消文字大小
                .setSubmitColor(Color.GRAY)//确定按钮文字颜色
                .setCancelColor(Color.GRAY)//取消按钮文字颜色
                .setContentTextSize(18)//滚轮文字大小
                .setCyclic(false, false, false)//循环与否
                .build();
        dwPicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                mTvDw.setText(mDwList.get(options1));
                dwID = mDwRawList.get(options1).getId();
            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(14)//确定和取消文字大小
                .setSubmitColor(Color.GRAY)//确定按钮文字颜色
                .setCancelColor(Color.GRAY)//取消按钮文字颜色
                .setContentTextSize(18)//滚轮文字大小
                .setCyclic(false, false, false)//循环与否
                .build();

    }

    public void onClickEwm(View view) {
        Intent intent = new Intent(this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE);
    }

    private boolean correct = false;

    public void onClickQuery(View view) {
        initQuery();
    }

    private void initQuery() {
        number = mEtNumber.getText().toString();
        HttpParams params = new HttpParams();
        params.put("supplierBatchID", number); //工序编号
        OkGoUtils.getInstance().post(this, URL.GET_MATERIAL, params, 1, true, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (200 == response.getCode()) {
                    correct = true;
                    String data = response.getDataInfo().toString();
                    IqbMateBean iqbMateBean = JSON.parseObject(data, IqbMateBean.class);

                    List<IqbMateBean.DataListBean> dataList = iqbMateBean.getDataList();
                    int size = dataList.size();
                    if (0 < size) {
                        IqbMateBean.DataListBean bean = dataList.get(0);
//                        bean.getBelong()
                        oid = bean.getOid();
                        supplierOid = bean.getSupplierOid();
                        supplierCode = bean.getSupplierCode();
                        substring = bean.getNumber();
                        mTvWlpcm.setText(number);
                        partID = bean.getPartID();
                        mTvWlbm.setText(partID);
                        mTvWlmc.setText(bean.getPartName());
                        mTvGys.setText(bean.getSupplierName());
                        mTvLjcsd.setText(bean.getChengShuDu());
                        mTvTzbb.setText(bean.getTuZhi());
                        mTvBc.setText(bean.getBanCi());

                        String createdTime = bean.getCreatedTime();
                        String substring = createdTime.substring(0, 10);
                        mTvWlrq.setText(bean.getWuliaotime());

                        int type = bean.getType();
                        switch (type) {
                            case 1:
                                mTvWllb.setText("成品");
                                break;
                            case 2:
                                mTvWllb.setText("半成品");
                                break;
                            default:
                                mTvWllb.setText("原材料");
                                break;
                        }


                        iqcNCheck = bean.getIqcNCheck();
                        if (1 == iqcNCheck) {
                            mTvIqcmj.setText("不免检");
                        } else {
                            mTvIqcmj.setText("免检");
                        }

                        mEtSl.setText("");
                        kfID = 10001;
                        mTvKf.setText("请选择(必选)");
                        dwID = 10001;
                        mTvDw.setText("请选择(必选)");
                        yxjID = 0;
                        yxjString = "低";
                        initShowTab(mTvYxjD, mTvYxjZ, mTvYxjG);
                        bzID = 1;
                        initShowTab(mTvBzWz, mTvBzBwz, null);
                        jybgID = 1;
                        initShowTab(mTvJybgWz, mTvJybgBwz, null);
                    }
                } else {
                    correct = false;
                    showToast(response.getMsg());
                }
            }

            @Override
            public void onError(Throwable e, int id) {

            }
        });
    }

    private void initShowTab(TextView one, TextView two, TextView three) {
        one.setBackgroundResource(R.drawable.m_border_13_blue);
        two.setBackgroundResource(R.drawable.m_border_13_99);
        one.setTextColor(getResources().getColor(R.color.blue2));
        two.setTextColor(getResources().getColor(R.color.color_99));
        if (three != null) {
            three.setBackgroundResource(R.drawable.m_border_13_99);
            three.setTextColor(getResources().getColor(R.color.color_99));
        }
    }

    /**
     * 提交来料
     */
    public void onSubmit(View view) {
        String sl = mEtSl.getText().toString();
        String psl = mEtPsl.getText().toString();


        if (!correct) {
            showToast("请输入正确的物料批次码");
            return;
        }

        if (sl.isEmpty()) {
            showToast("请输入总数量");
            return;
        }
        if (psl.isEmpty()) {
            showToast("请输入批数量");
            return;
        }
        if (10001 == dwID) {
            showToast("请选择单位");
            return;
        }
        if (10001 == kfID) {
            showToast("请选择库房");
            return;
        }

        HttpParams params = new HttpParams();
        params.put("fMmMaterialOid", oid); //
        params.put("fMmSupplierOid", supplierOid); //
        params.put("batchId", number); //物料批次码
        params.put("priority", yxjString); //优先级
        params.put("number1", sl); //数量
        params.put("batchNumber", psl); //批数量
        params.put("checkReport", jybgID); //检验报告完整度1完整；0不完整
        params.put("packageReport", bzID); //包装完整度1完整；0不完整
        params.put("fmMmstoreHouseOid", kfID); //库房ID
        params.put("fUserCreator", userId); //
        params.put("partId", partID); //物料编码
        params.put("isCheck", iqcNCheck);  //
        params.put("fmmUnitOid", dwID);  //

        LogUtils.e("data====" + params.toString());
        //   showToast("tijiao");
        OkGoUtils.getInstance().post(this, URL.ADD_IQC_CHECK, params, 2, true, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (200 == response.getCode()) {
                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    showToast("提交成功");
                    finish();
                } else {
                    showToast(response.getMsg());
                }
            }

            @Override
            public void onError(Throwable e, int id) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    final String result = bundle.getString(CodeUtils.RESULT_STRING);
                    mEtNumber.setText(result);
                    initQuery();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(IqcRegisterActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_kf) {  /**选择库房*/
            if (ObjectUtils.notEmpty(mKfList)) {
                kfPicker.setPicker(mKfList);
                kfPicker.show();
            }
        } else if (id == R.id.ll_dw) {  /**选择单位*/
            if (ObjectUtils.notEmpty(mDwList)) {
                dwPicker.setPicker(mDwList);
                dwPicker.show();
            }
        } else if (id == R.id.tv_yxj_d) {
            yxjID = 0;
            yxjString = "低";
            initShowTab(mTvYxjD, mTvYxjZ, mTvYxjG);
        } else if (id == R.id.tv_yxj_z) {
            yxjID = 1;
            yxjString = "中";
            initShowTab(mTvYxjZ, mTvYxjD, mTvYxjG);
        } else if (id == R.id.tv_yxj_g) {
            yxjID = 2;
            yxjString = "高";
            initShowTab(mTvYxjG, mTvYxjZ, mTvYxjD);
        } else if (id == R.id.tv_bz_wz) {
            bzID = 1;
            initShowTab(mTvBzWz, mTvBzBwz, null);
        } else if (id == R.id.tv_bz_bwz) {
            bzID = 0;
            initShowTab(mTvBzBwz, mTvBzWz, null);

        } else if (id == R.id.tv_jybg_wz) {
            jybgID = 1;
            initShowTab(mTvJybgWz, mTvJybgBwz, null);
        } else if (id == R.id.tv_jybg_bwz) {
            jybgID = 0;
            initShowTab(mTvJybgBwz, mTvJybgWz, null);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            //当isShouldHideInput(v, ev)为true时，表示的是点击输入框区域，则需要显示键盘，同时显示光标，反之，需要隐藏键盘、光标
            if (ToolUtils.isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    //处理Editext的光标隐藏、显示逻辑
                    mEtSl.clearFocus();
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
}
